#include "BaseForm.h"
#include <QFile>
#include <QDateTime>

BaseForm::BaseForm(QWidget *parent)
    : QWidget(parent)
{
    this->setFixedSize(1000,720);
    // this->setWindowFlag(Qt::FramelessWindowHint);

    init();
    initSignalAndSlots();

    return;

    FilePacket data;
    data.fileName = "发票_20250321.docx";
    data.targetAddress = "192.168.1.1";
    data.fileType = "docx";
    QFile file("C:\\Users\\Administrator\\Desktop\\发票_20250321.docx");
    if(file.open(QIODevice::ReadOnly))
    {
        data.fileData = file.readAll();
        m_TcpManager->sendFile(data);
    }

}

BaseForm::~BaseForm() {}

void BaseForm::init()
{
    m_ListWidget = new QListWidget(this);
    m_ListWidget->setFixedSize(240,690);
    m_ListWidget->move(0,50);

    m_OnLineNum = new QLabel(this);
    m_OnLineNum->setText("在线用户（0）");
    m_OnLineNum->move(0,0);
    QFont font("sans-serif", 17, QFont::Bold);
    m_OnLineNum->setFont(font);

    m_ListWidget->setSelectionMode(QAbstractItemView::NoSelection);

    m_TcpManager = new TcpManager(this);

    NewClient client;
    client.ip = "10.1.32.238";
    slot_NewClient(client);
}

void BaseForm::initSignalAndSlots()
{
    connect(m_TcpManager,SIGNAL(signal_NewClient(NewClient)),this,SLOT(slot_NewClient(NewClient)));
    connect(m_TcpManager,SIGNAL(signal_FilePacket(FilePacket)),this,SLOT(slot_FilePacket(FilePacket)));
    connect(m_TcpManager,SIGNAL(signal_MessagePacket(MessagePacket)),this,SLOT(slot_MessagePacket(MessagePacket)));
}

void BaseForm::slot_NewClient(const NewClient &data)
{
    if(m_ClientMap.contains(data.ip)) return;
    ClientItem * itemWidget = new ClientItem;
    itemWidget->setClientIP(data.ip);
    m_ClientMap[data.ip] = itemWidget;
    itemWidget->setClientName("客户端");
    itemWidget->setOnLineStat(true);
    QVBoxLayout* layout = new QVBoxLayout(itemWidget);
    itemWidget->setLayout(layout);
    QListWidgetItem *item = new QListWidgetItem(m_ListWidget);
    item->setSizeHint(itemWidget->size());
    m_ListWidget->setItemWidget(item, itemWidget);

    ChatWidget* chat = new ChatWidget(this);
    chat->move(260,0);
    chat->hide();
    m_ChatWidgetMap[data.ip] = chat;
    connect(chat,&ChatWidget::singal_SendMessage,m_TcpManager,&TcpManager::slot_SendMessage);
    connect(chat,&ChatWidget::singal_SendFile,m_TcpManager,&TcpManager::slot_SendFile);
    connect(chat,&ChatWidget::signal_UpdateFilePath,this,[=](QString filePath){
        m_FilePath = filePath;
    });

    connect(itemWidget,&ClientItem::signal_OpenChatWidget,this,[=](QString ClientIP){
        if(m_ClientMap.contains(ClientIP))
        {
            chat->setClientIP(ClientIP);
            chat->setClientName(m_ClientMap[ClientIP]->getClientName());
            chat->show();
            for(auto it = m_ClientMap.begin();it != m_ClientMap.end();it++)
            {
                if(it.key() == ClientIP) continue;
                it.value()->setUnSelecte();
            }
        }
    });
    m_OnLineNum->setText(QString("在线用户（%1）").arg(QString::number(m_ClientMap.size())));
}

void BaseForm::slot_FilePacket(const FilePacket &data)
{
    QString fileSavePath = QDir(m_FilePath).filePath(data.fileName);
    QFile file(fileSavePath);
    if(!file.open(QIODevice::WriteOnly))
    {
        qWarning() << "File Open Failed";
    }

    file.write(data.fileData);

    file.close();
}

void BaseForm::slot_MessagePacket(const MessagePacket &data)
{
    if((!m_ClientMap.contains(data.sourceAddress)) || (!m_ChatWidgetMap.contains(data.sourceAddress)))
    {
        qWarning() << "ip no exits";
        qWarning() << "data:" << data.sourceAddress << data.targetAddress << data.messageData;
        return;
    }
    m_ClientMap[data.sourceAddress]->setUnReadMsg();
    m_ChatWidgetMap[data.sourceAddress]->addMessage({
        data.messageData,
        QDateTime::currentMSecsSinceEpoch(),
        ":/iconFile/heardTest.png",
        false,  // 接收方消息
        0       // 文字类型
    });
}
